/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package redezeitor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Mauriverti
 */
public class MainWindow extends javax.swing.JFrame {

    /**
     * Creates new form MainWindow
     */
    private ArrayList<Roteador> routers = new ArrayList<>();
    private boolean router_matrix = false;
    
    public void printRouters() {

        if (routers.isEmpty()) {
            return;
        }

        String s = new String();
        s += "id -> [idDestino,distancia]\n\n";
        for (Roteador r : routers) {
            s += r.getRouterId() + " -> ";
            s += r.getLinks();
            s += "\n";
        }

        jTextArea.setText(s);
    }

    public void addRouter(Roteador r) {
        //r.setPos(routers.size());
        routers.add(r);
        
    }
    
    public void removeRouter (int id) {
        routers.remove(getPos(id));
    }
    
    public void removeLinks (int id) {
        for (Roteador router : routers) {
            router.removeLink(id);
        }
    }
    
    public void removeLink (int id1, int id2) {
        for (Roteador router : routers) {
            if (router.getRouterId() == id1) {
                router.removeLink(id2);
            }
            if (router.getRouterId() == id2) {
                router.removeLink(id1);
            }
        }
    }
    
    public MainWindow() {
        initComponents();
        this.setTitle("Trabalho de Redes - Jessica e Mauriverti");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea = new javax.swing.JTextArea();
        addRouterButton = new javax.swing.JButton();
        removeRouterButton = new javax.swing.JButton();
        checkSubNetworkButton = new javax.swing.JButton();
        addLinkButton = new javax.swing.JButton();
        JBShowMatrix = new javax.swing.JButton();
        JBExecute = new javax.swing.JButton();
        JBFunc = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jTextArea.setEditable(false);
        jTextArea.setColumns(20);
        jTextArea.setRows(5);
        jScrollPane1.setViewportView(jTextArea);

        addRouterButton.setText("Adicionar Roteador");
        addRouterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addRouterButtonActionPerformed(evt);
            }
        });

        removeRouterButton.setText("Remover Roteador");
        removeRouterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeRouterButtonActionPerformed(evt);
            }
        });

        checkSubNetworkButton.setText("Checar Subrede");
        checkSubNetworkButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkSubNetworkButtonActionPerformed(evt);
            }
        });

        addLinkButton.setText("Adicionar Link");
        addLinkButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addLinkButtonActionPerformed(evt);
            }
        });

        JBShowMatrix.setText("Roteador/Matriz");
        JBShowMatrix.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBShowMatrixActionPerformed(evt);
            }
        });

        JBExecute.setText("Executar");
        JBExecute.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBExecuteActionPerformed(evt);
            }
        });

        JBFunc.setText("Funcionar");
        JBFunc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBFuncActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(addRouterButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(removeRouterButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(addLinkButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(checkSubNetworkButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(JBShowMatrix, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(JBExecute, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(JBFunc))
            .addComponent(jScrollPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(addRouterButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(removeRouterButton)
                        .addComponent(checkSubNetworkButton)
                        .addComponent(addLinkButton)
                        .addComponent(JBShowMatrix)
                        .addComponent(JBExecute)
                        .addComponent(JBFunc)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void addRouterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addRouterButtonActionPerformed

        System.out.println("addRouter");

        AddRouter a = new AddRouter(this);
        a.setVisible(true);


    }//GEN-LAST:event_addRouterButtonActionPerformed


    private void checkSubNetworkButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkSubNetworkButtonActionPerformed

        if (routers.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Nenhum Roteador Adicionado", "", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        /*Roteador aux = routers.get(0);

        String s = new String();
        s = "SubRede: " + aux.getStringSubNetwork() + "\n";

        boolean ok = true;
        for (Roteador router : routers) {
            if (router.getSubNetwork() != aux.getSubNetwork()) {
                s += "Roteador " + router.getRouterId() + " mal configurado, subrede: " + router.getStringSubNetwork() + "\n";
                ok = false;
            }
        }

        if (ok) {
            s += "Todos os roteadores na mesma subrede";
        }
        JOptionPane.showMessageDialog(null, s, "", JOptionPane.INFORMATION_MESSAGE);
        */
        
        for (Roteador router: routers) {
            for (Link link : router.c.links) {
                link.checkSubNetwork();
            }
        }
        
        printRouters();
    }//GEN-LAST:event_checkSubNetworkButtonActionPerformed

    private void addLinkButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addLinkButtonActionPerformed

        if (routers.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Nenhum Roteador Adicionado", "", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        AddLink a = new AddLink(this);
        a.setVisible(true);

    }//GEN-LAST:event_addLinkButtonActionPerformed

    private void removeRouterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeRouterButtonActionPerformed

        if (routers.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Nenhum Roteador Adicionado", "", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        RemoveRouter r = new RemoveRouter(this);
        r.setVisible(true);
    }//GEN-LAST:event_removeRouterButtonActionPerformed

    public ArrayList<Integer> getIds() {
        
        ArrayList<Integer> ids = new ArrayList<>();
        
        for (Roteador router : routers) {
            ids.add(router.getRouterId());
        }
        
        return ids;
    }
    
    private void JBShowMatrixActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBShowMatrixActionPerformed

        for (Roteador router : routers) {
            router.setMatrix(getIds());
        }
        
    }//GEN-LAST:event_JBShowMatrixActionPerformed

    private void JBExecuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBExecuteActionPerformed

        for (Roteador router : routers) {
            router.setMatrix(getIds());
        }
        
        
        
        if (routers.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Nenhum Roteador Adicionado", "", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        for (Roteador router : routers) {
            router.start();
        }
        
        for (Roteador router : routers) {
            try {
                router.c.cliente();
            } catch (IOException ex) {
                Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
    }//GEN-LAST:event_JBExecuteActionPerformed

    private void JBFuncActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBFuncActionPerformed

        String s = new String();
        for (Roteador router : routers) {
            s += router.showMatrix() + "\n\n";
        }
        
        jTextArea.setText(s);
        
    }//GEN-LAST:event_JBFuncActionPerformed

    public void addLink(int idRouter1, int idRouter2, int mask1, int mask2, int ip1, int ip2, int distance) {

        int pos1 = getPos(idRouter1);
        int pos2 = getPos(idRouter2);

        if (pos1 > -1 && pos2 > -1) {
            routers.get(pos1).addLink(idRouter2, ip1, ip2, mask1, mask2, distance);
            routers.get(pos2).addLink(idRouter1, ip2, ip1, mask2, mask1, distance);
        }

    }

    public int countRouters() {

        return routers.size();
    }

    public int getRouterID(int pos) {
        if (pos >= routers.size()) {
            return -1;
        }
        return routers.get(pos).getRouterId();
    }

    public int getPos(int id) {
        for (int i = 0; i < routers.size(); i++) {
            Roteador r = routers.get(i);
            if (r.getRouterId() == id) {
                return i;
            }
        }
        return -1;
    }

    public boolean existsID(int id) {
        for (Roteador router : routers) {
            if (router.getRouterId() == id) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainWindow().setVisible(true);

            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton JBExecute;
    private javax.swing.JButton JBFunc;
    private javax.swing.JButton JBShowMatrix;
    private javax.swing.JButton addLinkButton;
    private javax.swing.JButton addRouterButton;
    private javax.swing.JButton checkSubNetworkButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea;
    private javax.swing.JButton removeRouterButton;
    // End of variables declaration//GEN-END:variables
}
